import $router from '@/common/router/router'

// @ts-ignore
import NProgress from 'nprogress'
import {useRouteStore} from "@/common/store/modules/route";
import {refreshMenu, refreshUserInfo} from "@/common/api/common";
import {useLayoutStore} from "@/common/store/modules/layout";
import {getRefreshToken, getToken} from "@/common/util/cache";

//白名单路由
let publicRouter = ['/login', '/index', '/404', '/error']

NProgress.configure({showSpinner: false});

$router.beforeEach(async (to, from, next) => {
    //console.log("【NowToPath】", to.path)

    NProgress.start()
    useLayoutStore().windowLoading = true;

    //检查页面刷新
    await checkF5(to, from, next)

    //白名单放行
    if (publicRouter.indexOf(to.path) != -1) {
        next()
        return;
    }
    //检查
    check404(to, from, next)
})

$router.afterEach(() => {
    NProgress.done()
    useLayoutStore().windowLoading = false;
})

//首次登录拦截
let check404 = (to, from, next) => {
    let has = false;
    let routes = $router.getRoutes()
    routes.filter(e => {
        if (e.path == to.path) {
            has = true;
        }
    })
    if (has) {
        next()
    } else {
        next("/404")
    }
}

//首次登录拦截
let checkToken = (to, from, next) => {
    let token = getToken()
    let refreshToken = getRefreshToken()
    return !(!token || !refreshToken);
}

//检查页面刷新
async function checkF5(to, from, next) {
    if (useRouteStore().isF5) {

        //关闭刷新状态
        useRouteStore().isF5 = false

        //检查Token,不存在Token
        // 1.关闭刷新状态
        // 2.转发 /login 页面
        let checkTokenStatus = checkToken(to, from, next);
        if (!checkTokenStatus) {
            next(`/login` + redirectPath(to))
            return;
        }

        //查用户、查菜单、动态添加路由
        let status1 = await refreshUserInfo()
        let status2 = await refreshMenu()
        //网络请求异常，重定向到redirect
        if (!status1 || !status2) {
            //console.log("网络请求异常，重定向到redirect")
            next(`/index` + redirectPath(to));
            return;
        }

        // hack方法 确保addRoutes已完成
        next({...to, replace: true})
    }
}

//返回重定向路径
let redirectPath = (to) => {
    if (publicRouter.indexOf(to.path) == -1) {
        return `?redirect=${to.path}`
    } else {
        return ''
    }
}